<template>
  <div class='wrapper'>
    <div id="map"/>
    <div id="popup" class="ol-popup" v-show="isPopup">
      <a href="#" id="popup-closer" @click="closePopup" class="ol-popup-closer"/>
      <div id="popup-content">
        <ul v-if="markType === 'car'">
          <li class="title-box">
            <span class="circle-icon"/>
            <span>车辆号：{{device&&device.deviceGis&&device.deviceGis.carNumber}}</span>
          </li>
          <li class="popup-content-item">
            <span class="span-item">使用人：{{device&&device.deviceGis&&device.deviceGis.deviceBind&& device.deviceGis.deviceBind.userName ?device.deviceGis.deviceBind.userName:'--'}}</span>
          </li>
          <li class="popup-content-item">
            <span class="span-item">所属单位：{{device&&device.deviceGis&&device.deviceGis.deptName}}</span>
          </li>
          <li class="popup-content-item">更新时间：{{device&&device.deviceGis&&device.deviceGis.lastTime}}</li>
        </ul>
        <ul v-else>
          <li class="title-box">
            <span class="circle-icon"/>
            <span>用户id：{{userInfo&&userInfo.userId?userInfo.userId:'--'}}</span>
          </li>
          <li class="popup-content-item">
            <span class="span-item">用户名：{{userInfo&&userInfo.userName?userInfo.userName:'--'}}</span>
          </li>
          <li class="popup-content-item">
            <span class="span-item">所属单位：{{userInfo&&userInfo.deptName?userInfo.deptName:'--'}}</span>
          </li>
          <li class="popup-content-item">更新时间：{{userInfo&&userInfo.updateTime?userInfo.updateTime:'--'}}</li>
        </ul>
      </div>


    </div>
  </div>
</template>

<script>
    import {transform} from 'ol/proj.js'
    import 'ol/ol.css'
    import Map from 'ol/Map'
    import View from 'ol/View'
    import Style from 'ol/style/Style'
    import Stroke from 'ol/style/Stroke'
    import Icon from 'ol/style/Icon'
    import Overlay from 'ol/Overlay'
    import Feature from 'ol/Feature'
    import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
    import VectorSource from 'ol/source/Vector';
    import TileWMS from 'ol/source/TileWMS';
    import {XYZ} from 'ol/source'
    import TileJSON from 'ol/source/TileJSON';


    import car from '@/assets/images/marker/car.png'
    import wheelbarrow from '@/assets/images/marker/wheelbarrow.png'
    import elevator_car from '@/assets/images/marker/elevator_car.png'
    import work_ladder from '@/assets/images/marker/work_ladder.png'
    import water_release_truck from '@/assets/images/marker/water_release_truck.png'
    import end from '@/assets/images/marker/end.png'
    import start from '@/assets/images/marker/start.png'
    import pass from '@/assets/images/marker/pass.png'
    import user from '@/assets/images/marker/user.png'

    export default {
        name: 'Map',

        props: {
            typeName: {
                type: [String],
                required: true
            },
            userInfo: {
                type: [Object, Function],
                required: true
            },
            iconName: {
                type: String,
                required: true
            }
        },
        data() {
            return {
                map: {},
                tenantMap: {},//地图配置文件
                isPopup: false,//是否显示地图弹框
                markType: '',//坐标点类型
                mapLayer: {
                    draw: {
                        name: 'draw',
                        type: 'Polygon'
                    },
                    realTile: {
                        name: 'realTile'
                    },
                    trackPlayback: {
                        name: 'trackPlayback',
                        route: new Feature({
                            type: 'route'
                        }),
                        geo: new Feature({
                            type: 'pass'
                        }),
                        start: new Feature({
                            type: 'start'
                        }),
                        end: new Feature({
                            type: 'end'
                        })
                    }
                },
                mapParameter: {
                    // mapUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
                    // mapUrl: 'http://www.google.cn/maps/vt?lyrs=s@189&gl=en&x={x}&y={y}&z={z}',
                    // lngCenter: 103.9535836,
                    // latCenter: 30.5822868,
                    mapZoom: 15,
                    mapCenter: "104.45544, 30.323124",
                    minZoom: 2,
                    maxZoom: 23,
                    from_epsg: 'EPSG:4326',
                    to_epsg: 'EPSG:3857',
                    iconStyles: {
                        'route': new Style({
                            stroke: new Stroke({
                                width: 4, color: [237, 212, 0, 0.8]
                            })
                        }),
                        //人图标
                        'user': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.05,
                                src: user
                            })
                        }),
                        // 车图标
                        'powerless': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.5,
                                src: car
                            })
                        }),
                        // 客梯车
                        'elevator_car': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: elevator_car
                            })
                        }),
                        // 放水车
                        'water_release_truck': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: water_release_truck
                            })
                        }),
                        // 手推车
                        'wheelbarrow': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: wheelbarrow
                            })
                        }),
                        // 工作梯
                        'work_ladder': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: work_ladder
                            })
                        }),
                        'start': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: start
                            })
                        }),
                        'end': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: end
                            })
                        }),
                        'pass': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: pass
                            })
                        })
                    }
                },
                properties: [],
                device: {
                    deviceGis: {
                        lng: undefined,
                        lat: undefined,
                        createTime: undefined,
                        number: undefined
                    }
                }
            }
        },
        mounted() {
            this.getInitData();
        },
        sockets: {},
        methods: {
            // 获取初始化数据
            getInitData() {
                const param = {
                    userId: this.userInfo.userId
                }
                const url = baseUrl + '/powerless/person/findUserById'
                this.$get(url, param).then(data => {
                    const tenantMap = data.obj&&data.obj.tenantMap ? data.obj.tenantMap : {};
                    console.log(tenantMap, 'tenantMap')
                    this.mapParameter = Object.assign(this.mapParameter, tenantMap);
                    console.log(this.mapParameter, 'this.mapParameter')
                    // 初始化地图
                    this.initMap();
                    // console.log(data,'// 获取初始化数据')
                })
            },
            // 谷歌底图
            getBaseLayer(lyr) {
                let prj = 'EPSG:3857';
                let layer = new TileLayer({
                    source: new XYZ({
                        url: this.mapParameter.mapUrl,
                        wrapX: false,
                        projection: prj,
                        // crossOrigin: 'Anonymous',
                    }),
                });
                return layer;
            },
            // 天府机场底图
            getTFLayer(lyr) {
                let prj = 'EPSG:3857';
                let layer = new TileLayer({
                    source: new XYZ({
                        attributions: 'Copyright:© 2013 ESRI, i-cubed, GeoEye',
                        //url:  'https://services.arcgisonline.com/arcgis/rest/services/ESRI_Imagery_World_2D/MapServer/tile/{z}/{y}/{x}',
                        //url:  'http://192.168.0.202:6080/arcgis/rest/services/TEST/T1F1_Tile_ZSNJ_Normal_Lable_wgs84_test/MapServer/tile/{z}/{y}/{x}',
                        url: 'http://39.98.156.246:6080/arcgis/rest/services/TEST/ZT_Tile_TFJC_Normal_Label/MapServer/WMTS/tile/1.0.0/TFJC_ZT_Tile_TFJC_Technology_Label_WGS/default/default/{z}/{y}/{x}',
                        //url:  'http://39.98.156.246:6080/arcgis/rest/services/TEST/test4/MapServer/tile/{z}/{y}/{x}',
                        maxZoom: 8,
                        minZoom: 0,
                        projection: 'EPSG:4326',
                        tileSize: 256, // the tile size supported by the ArcGIS tile service
                        maxResolution: 180 / 256, // Esri's tile grid fits 180 degrees on one 512 px tile
                        //minResolution: 0.0000023794610058302894,
                        wrapX: true,
                        format: 'image/png',
                        sphericalMercator: false,
                    }),
                });
                return layer;
            },
            //  哈尔滨底图
            getWMSLayer() {
                // let url = 'http://119.23.226.237:8080/geoserver/sf/wms?service=WMS&version=1.1.0';
                let layer = new TileLayer({
                    source: new TileWMS({
                        url: this.mapParameter.mapUrl,
                        params: {
                            'FORMAT': 'image/png',
                            'LAYERS': `sf:${this.mapParameter.layerName}`
                            // 'LAYERS': 'sf:heb'
                        }
                    }),
                })
                return layer;
            },
            getTDTLayer () {
              // let epsg = 'EPSG:4326';
              // let projection = getProjection(epsg);
              let source = new XYZ({
                // url: 'http://t4.tianditu.com/DataServer?T=vec_w&tk=7f925b507bf05b22c92a84ed34fbd6af&x={x}&y={y}&l={z}'
                url: 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}@2x.jpg90?access_token=pk.eyJ1IjoicGVuZ3lpbWFwIiwiYSI6ImNrdGR5dDM2ejJrdHQybnEyNWJhc3ljNDAifQ.UOWZ6PvFUbyvyAQcU1EOJA'

              })
              let tileLayer = new TileLayer({
                id: 'tileLayer',
                title: '天地图',
                layerName: 'baseMap',
                source: source
              })
              // 标注图层
              let sourceMark = new XYZ({
                url: 'http://t3.tianditu.com/DataServer?T=cva_w&tk=7f925b507bf05b22c92a84ed34fbd6af&x={x}&y={y}&l={z}'
              })
              let tileMark = new TileLayer({
                id: 'tileMark',
                title: '标注图层',
                layerName: 'baseMap',
                source: sourceMark

              })
              let MapboxLayer = new TileLayer({
                source: new TileJSON({
                  url: "https://api.tiles.mapbox.com/v4/mapbox.satellite.json?secure&access_token=pk.eyJ1IjoicGVuZ3lpbWFwIiwiYSI6ImNrdGR5dDM2ejJrdHQybnEyNWJhc3ljNDAifQ.UOWZ6PvFUbyvyAQcU1EOJA",
                  crossOrigin: 'anonymous',
                }),
              })
              // 卫星图像
              let sourceSatellite = new XYZ({
                url: 'http://t3.tianditu.com/DataServer?T=img_w&tk=7f925b507bf05b22c92a84ed34fbd6af&x={x}&y={y}&l={z}'
              })
              let tileSatellite = new TileLayer({
                id: 'tileSatellite',
                title: '卫星图',
                layerName: 'baseMap',
                source: sourceSatellite

              })

              // 天地图地形地图
              let map_ter = new TileLayer({
                id: 'map_ter',
                title: '天地图地形',
                layerName: 'baseMap',
                source: new XYZ({
                  url: 'http://t4.tianditu.com/DataServer?T=ter_w&tk=7f925b507bf05b22c92a84ed34fbd6af&x={x}&y={y}&l={z}'
                })
              })
              let map_cta = new TileLayer({
                id: 'map_cta',
                title: '天地图标注',
                layerName: 'baseMap',
                source: new XYZ({
                  url: 'http://t4.tianditu.com/DataServer?T=cva_w&tk=7f925b507bf05b22c92a84ed34fbd6af&x={x}&y={y}&l={z}'
                })
              })
              // let prj = 'EPSG:4326'
              // let layer = new TileLayer({
              //   source: new XYZ({
              //     url: 'http://t0.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={x}&TILECOL={y}&tk=7f925b507bf05b22c92a84ed34fbd6af',
              //     // wrapX: false,
              //     projection: prj
              //   })
              // })
              // 高德地图
              let AMapLayer = new TileLayer({
                source: new XYZ({
                  url: 'http://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
                })
              });

              // 高德地图
              let AMapLayerL = new TileLayer({
                source: new XYZ({
                  url: 'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
                })
              });
              return tileLayer
            },
            // 初始化地图
            initMap() {
                console.log(this.typeName, 'type1')
                console.log(this.userInfo, 'use')
                const that = this;
                const container = document.getElementById('popup')
                const overlay = new Overlay({
                    id: 'point',
                    element: container,
                    autoPan: true,
                    autoPanAnimation: {
                        duration: 250
                    },
                    offset: [0, -23]
                });
                // const initDrawLayer = new VectorLayer({
                //     name: this.iconName,
                //     source: new VectorSource({
                //         features: []
                //     }),
                //     style: function (feature) {
                //         return that.mapParameter.iconStyles[feature.get('type')];
                //     },
                // })

              const initDrawLayer = new VectorLayer({
                name: this.iconName,
                source: new VectorSource({
                  wrapX: false,
                  visible: false
                }),
                style: function (feature) {
                  return that.mapParameter.iconStyles[feature.get('type')] ? that.mapParameter.iconStyles[feature.get('type')] : that.mapParameter.iconStyles['draw']
                }
              })
                let layers = [this.getTDTLayer(), initDrawLayer]
                this.map = new Map({
                    target: 'map',
                    overlays: [overlay],
                    layers: layers,
                    // layers: [
                    //     this.mapParameter.mapLayer === 'WMSLayer' ?
                    //         this.getWMSLayer() : this.mapParameter.mapLayer === 'tianfuLayer' ?
                    //         this.getTFLayer() : this.getBaseLayer(), initDrawLayer],
                    view: new View({
                        center: this.transformSelf(this.mapParameter.mapCenter.split(',')[0], this.mapParameter.mapCenter.split(',')[1]),
                        zoom: this.mapParameter.mapZoom,
                        minZoom: this.mapParameter.minZoom,
                        maxZoom: this.mapParameter.maxZoom
                    })
                })
                this.onclickPoint((that, feature) => {
                    // console.log('hahah', feature)
                    const properties = feature.getProperties();
                    that.markType = properties.device.type;
                    if (that.typeName === 'car') {
                      console.log(1,'typeName ===')
                        if (that.markType === 'car') {
                          console.log(1,'markType ===')
                            this.device = properties.device;
                          console.log(this.device,'this.device.deviceGis')
                            if (this.device && this.device.deviceGis) {

                                const latestLocation = this.device.deviceGis.latestLocation;
                                if (latestLocation) {
                                    const lng = latestLocation.split(',')[0];
                                    const lat = latestLocation.split(',')[1];
                                    const result = that.transformSelf(lng, lat)
                                    const overlay = that.map.getOverlayById('point')
                                    console.log(this.device, 'this.device')
                                    overlay.setPosition(result);
                                }
                            }
                        } else {
                          console.log(this.userInfo,'this.userInfo')
                            const lng = this.userInfo.lng;
                            const lat = this.userInfo.lat;
                            const result = that.transformSelf(lng, lat)
                            const overlay = that.map.getOverlayById('point')
                            overlay.setPosition(result);
                        }

                    } else if (that.typeName == 'user') {
                        const lng = this.userInfo.lng;
                        const lat = this.userInfo.lat;
                        const result = that.transformSelf(lng, lat)
                        const overlay = that.map.getOverlayById('point')
                        overlay.setPosition(result);
                    }
                    this.isPopup = true;
                })
                this.$emit('getDeviceCarMap', this.map, this.mapParameter, this.mapLayer)
                this.$emit('initDrawLayer')
            },
            /**
             * 操作某一个source工具方法
             */
            operationSource(name, fun, clear) {
                const layers = this.map.getLayers().getArray()
                layers.length && layers.forEach(layer => {
                    const properties = layer.getProperties()
                    if (properties.name === name) {
                        const source = layer.getSource()
                        if (clear) {
                            source && source.clear()
                        }
                        fun(source, layer)
                    }
                })
            },
            transformSelf(lng, lat) {
                return transform([lng, lat], this.mapParameter.from_epsg, this.mapParameter.to_epsg)
            },
            clearSource() {
                const layers = this.map.getLayers().getArray()
                layers.length && layers.forEach(layer => {
                    const source = layer.getSource()
                    source && source.clear()
                })
            },

            /**
             * 关闭设备信息弹出
             */
            closePopup() {
                const overlays = this.map.getOverlays().getArray()
                overlays.length && overlays.forEach(overlay => overlay.setPosition(undefined))
                const olPopupCloser = document.getElementsByClassName('ol-popup-closer')
                this.$emit('changeOpenPopup')
                this.isPopup = false;
                for (const olPopupCloserElement of olPopupCloser) {
                    olPopupCloserElement.blur()
                }
            },
            /**
             * 监听点击事件
             */
            onclickPoint(fun) {
                const that = this
                this.map.on('singleclick', function (evt) {
                    console.log('dianji')
                    const pixel = that.map.getEventPixel(evt.originalEvent) // 获取鼠标当前位置
                    let ly = null
                    let feature = null
                    that.map.forEachFeatureAtPixel(pixel, function (f, layer) { // 获取鼠标位置的要素
                        if (layer) {
                            if (feature == null) {
                                feature = f
                                ly = layer
                            }
                        }
                    })
                    if (feature) {
                        console.log('11111')
                        fun(that, feature)
                    }
                })
            },
            setDevice(device) {
                this.device = device;
            }
        },
    }
</script>

<style scoped>
  .app-main {
    height: 100%;
  }

  .wrapper {
    position: relative;
    flex: 1;
    top: 0;
    left: 0;
    height: 100%;
  }

  .toolbars.el-col {
    height: calc(100vh - 4px);
  }

  .toolbars {
    position: absolute;
    width: 100%;
    height: 55px;
    float: right;
  }

  #map {
    position: relative;
    flex: 1;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }

  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .circle-icon {
    margin-right: 3px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    overflow: hidden;
    background-color: #42b983;
  }

  .ol-popup {
    position: absolute;
    background-color: white;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    /*padding: 15px;*/
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 190px;
    margin-bottom: 10px;
    z-index: 4;
    padding: 20px;
  }

  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
  }

  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
  }

  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 6px;
    right: 8px;
  }

  .ol-popup-closer:after {
    content: "✖";
    color: #888;
  }

  .title-box {
    display: flex;
    padding-bottom: 10px;
    align-items: center;
    color: #262626;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    border-bottom: 1px solid #ccc;
  }

  .circle-icon {
    margin-right: 3px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    overflow: hidden;
    background-color: #42b983;
  }

  .popup-content-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
    color: #999;
  }

  .span-item {
    flex: 1;
  }
</style>
